package com.android.antelopeapp.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.antelopeapp.R;
import com.android.antelopeapp.activity.BaseActivity;
import com.android.antelopeapp.common.SelectableViewList;
import com.android.antelopeapp.common.SelectableViewList.Selectable;
import com.android.antelopeapp.constant.ApiConfig;
import com.android.antelopeapp.constant.MsgConfig;
import com.android.antelopeapp.network.GsonRequest;
import com.android.antelopeapp.network.NetworkManager;
import com.android.antelopeapp.utils.NetworkUtils;
import com.android.antelopeapp.view.Commodity.CommodityListView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.lyhw.model.Commodity;
import com.lyhw.model.Type;
import com.lyhw.model.beanwraper.WraperFactory;

import java.util.ArrayList;
import java.util.List;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

/**
 * @author phk
 *         商品分类页面
 */
public class CommodityFragment extends Fragment {
    ViewGroup mContainer;
    private RecyclerView mIndexRecView;
    private ViewPager mViewPager;
    private Handler handler;
    public static int INIT=1;
    private List<Type> mTypes=new ArrayList<>();
    public static final String ALL_TYPES_NAME="全部";

    public BaseActivity getBaseActivity(){
        return (BaseActivity)(this.getActivity());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mContainer = container;
        final View rootView = inflater.inflate(R.layout.fragment_cg, container, false);
        mTypes.add(new Type(ALL_TYPES_NAME));
        initCGTab(rootView);

        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if(msg.what==INIT){
                    mIndexRecView.getAdapter().notifyDataSetChanged();
                    initViewPager(rootView);
                }
            }
        };
        return rootView;
    }

    /**
     * 循环遍历,将不重复的类型加入列表内
     * */
    private int updateTypes(List<Type> types){
        int len = mTypes.size();
        int res=0;
        for(Type type:types){
            int i=1;
            for(i=1;i<len;i++){
                if(mTypes.get(i).getTypeid().equals(type.getTypeid())){
                    break;
                }
            }
            if(i==len){
                mTypes.add(type);
                res++;
            }
        }
        return res;
    }

    /**
     * 修复未联网情况下的重新加载，另外一个页面点击进来如果内容为空总是进行重新加载
     */
    public void judgeReload(){
        Log.v("list size",mTypes.size()+"");
        if(mTypes.size()==1){
            asynUpdateTypes();
        }
    }

    /**
     * 初始化类目列表
     */
    private void asynUpdateTypes() {
        if(!NetworkUtils.isNetworkConnected(getActivity())){
            ((BaseActivity)getActivity()).sendToastMsg(MsgConfig.NETWORK_FAILED);
        }else{
            String url = ApiConfig.REQUEST_GOODS_TYPES;
            GsonRequest<WraperFactory.TypeWraper> grequest=new GsonRequest<WraperFactory.TypeWraper>(
                    url,
                    WraperFactory.TypeWraper.class,
                    null,
                    new Response.Listener<WraperFactory.TypeWraper>() {
                        @Override
                        public void onResponse(WraperFactory.TypeWraper response) {
                            if(updateTypes(response.getData())!=0) {
                                handler.sendEmptyMessage(INIT);
                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            BaseActivity activity=(BaseActivity)(CommodityFragment.this.getActivity());
                            activity.sendToastMsg(MsgConfig.GET_ITEMS_FAILURE);

                        }
                    });
            NetworkManager.getInstance(this.getActivity()).getRequestQueue().add(grequest);
        }
    }

    /**
     * 初始化上方分类栏
     */
    private void initCGTab(View rootView) {
        mIndexRecView = (RecyclerView) rootView.findViewById(R.id.cat_index_rec);
        // 创建一个线性布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager(this.getActivity());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        // 设置布局管理器
        mIndexRecView.setLayoutManager(layoutManager);
        mIndexRecView.setHasFixedSize(false);
        mIndexRecView.setAdapter(new CGRecyAdapter());
        asynUpdateTypes();
    }

    /**
     * 初始化下方viewpager作为多种商品列表的容器
     */
    private void initViewPager(View rootView) {
        CGPagerAdapter adapter = new CGPagerAdapter(mTypes.size());
        mViewPager = (ViewPager) rootView.findViewById(R.id.cat_view_pager);
        mViewPager.setAdapter(adapter);
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //tab需要初始化
                CGRecyAdapter adapter = (CGRecyAdapter) mIndexRecView.getAdapter();
                adapter.select(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        //选择第一个tab
        ((CGRecyAdapter) (mIndexRecView.getAdapter())).select(0);
    }

    /**
     * 主分类列表用RecyclerView实现
     * CGRecyAdapter作为它的adpater
     */
    public  class CGRecyAdapter extends RecyclerView.Adapter<CGRecyAdapter.ViewHolder> {
        /**
         * 列表中的view均为可选的
         */
        SelectableViewList svl;
        public CGRecyAdapter() {
            super();
            svl = new SelectableViewList() {
                @Override
                public void onSelected(int pos) {
                    Log.v("GListAdapter ", "onSelected pos=" + pos + " cat=" + mTypes.get(pos).getTypename());
                    //renderGridView(mTexts[pos]);
                    //如果不是第一次选择，则滚动至合适的位置
                    if (svl.getCurSelectedPos() != SelectableViewList.NONE) {
                        //如果原来的位置在当前位置的左边，则需要向左挪一个
                        if (svl.getCurSelectedPos() < pos) {
                            if (mIndexRecView.getAdapter().getItemCount() > pos + 1) {
                                mIndexRecView.scrollToPosition(pos + 1);
                            }
                        }
                        //否则向右移一个位置
                        else if (pos > 0) {
                            mIndexRecView.scrollToPosition(pos - 1);
                        }
                    }
                    if (pos != mViewPager.getCurrentItem()) {
                        mViewPager.setCurrentItem(pos);
                    }
                }
            };
        }

        @Override
        public int getItemCount() {
            return mTypes.size();
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_cg_index_item, parent, false);
            ViewHolder holder = new ViewHolder(view);
            return holder;
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, final int position) {
            Log.v("GoodsCategoryFragment.PagerAdapter", "onBindviewHolder pos:" + position);
            //将更新的ViewHolder添加到SelectableViewList中
            svl.putItem(position, holder);
            holder.mTextView.setText(mTypes.get(position).getTypename());
            holder.mTextView.setSelected(svl.getCurSelectedPos() == position);//需要重设控件是否被选择
            holder.mTextView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.v("GListAdapter", "OnClick first index " + position);
                    svl.select(position);
                }
            });
        }

        public void select(int pos) {
            svl.select(pos);
        }

        public class ViewHolder extends RecyclerView.ViewHolder implements Selectable {
            public TextView mTextView;

            /**
             * @param itemView
             * @Description: todo
             */
            public ViewHolder(View itemView) {
                super(itemView);
                mTextView = (TextView) itemView.findViewById(R.id.cg_first_index);
            }

            @Override
            public void setSelected(boolean state) {
                Log.v("CGRecyAdapter.ViewHolder", this.hashCode() + "setSelected " + state);
                mTextView.setSelected(state);
            }
        }
    }

    /**
     * ViewPager 的adapter
     * 多个商品列表用一个viewpager来保存
     * 当实例化一个页面时，则加载该页面的列表
     */
    private class CGPagerAdapter extends PagerAdapter {
        List<ListView> mList;
        int mMaxSize;

        private CGPagerAdapter(int mMaxSize) {
            this.mMaxSize = mMaxSize;
            mList = new ArrayList<>(mMaxSize);
        }

        /**
         * 获取pos位置上的listview
         * 若listview不存在，则先创建一个
         */
        private ListView getListView(int pos) {
            while (mList.size() <= pos || mList.get(pos) == null) {
                final CommodityListView lv = new CommodityListView(CommodityFragment.this.getActivity());
                lv.setTypeId(mTypes.get(pos).getTypeid());
                lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Commodity item = (Commodity)lv.getItemAtPosition(position);
                        getBaseActivity().showItemDetail(item.getTitle(),item.getUid(),item.getSource());
                    }
                });
                lv.init(getBaseActivity());
                mList.add(lv);
            }
            return mList.get(pos);
        }

        @Override
        public int getCount() {
            return this.mMaxSize;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ((ViewPager) container).addView(getListView(position));
            return mList.get(position);
        }

        @Override
        public void destroyItem(View container, int position, Object object) {
            ((ViewPager) container).removeView(mList.get(position));
        }
    }
}